var layer = layui.layer,
    form = layui.form,
    element = layui.element,
    laydate = layui.laydate,
    upload = layui.upload,
    table = layui.table;

// 通用提交
form.on('submit(*)', function (data) {
    var index = layer.msg('提交中，请稍候', {
        icon: 16,
        time: false,
        shade: 0.3
    });
    $(data.elem).attr('disabled', true);
    $.ajax({
        url: data.form.action,
        type: data.form.method,
        dataType: 'json',
        data: $(data.form).serialize(),
        success: function (result) {
            if (result.code === 1 && result.url != '') {
                setTimeout(function () {
                    location.href = result.url;
                }, 1000);
            } else {
                $(data.elem).attr('disabled', false);
            }
            layer.close(index);
            layer.msg(result.msg, {icon: 1});
        },
        error: function (xhr, state, errorThrown) {
            layer.close(index);
            layer.msg(state + '：' + errorThrown, {icon: 2});
        }
    });
    return false;
});
// 父窗口通用提交(表格无刷新关闭)
form.on('submit(t)', function (data) {
    var index = layer.msg('提交中，请稍候', {
        icon: 16,
        time: false,
        shade: 0.3
    });
    $.ajax({
        url: data.form.action,
        type: data.form.method,
        dataType: 'json',
        data: $(data.form).serialize(),
        success: function (result) {
            if (result.code === 1) {
                setTimeout(function () {
                    var ifrmae = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(ifrmae);
                    parent.layui.table.reload('tableList');
                }, 1000);
            }
            layer.close(index);
            layer.msg(result.msg, {icon: 1});
        },
        error: function (xhr, state, errorThrown) {
            layer.close(index);
            layer.msg(state + '：' + errorThrown, {icon: 2});
        }
    });
    return false;
});
// 父窗口通用提交(非表格页面刷新)
form.on('submit(i)', function (data) {
    //onsole.log(data.form)
    var index = layer.msg('提交中，请稍候', {
        icon: 16,
        time: false,
        shade: 0.3
    });
    $.ajax({
        url: data.form.action,
        type: data.form.method,
        dataType: 'json',
        data: $(data.form).serialize(),
        success: function (result) {
            if (result.code === 1) {
                setTimeout(function () {
                    parent.location.reload();
                }, 1000);
            }
            layer.close(index);
            layer.msg(result.msg, {icon: 1});
        },
        error: function (xhr, state, errorThrown) {
            layer.close(index);
            layer.msg(state + '：' + errorThrown, {icon: 2});
        }
    });
    return false;
});
// 通用开关
form.on('switch(*)', function (data) {
    var index = layer.msg('修改中，请稍候', {
        icon: 16,
        time: false,
        shade: 0.3
    });
    // 参数
    var obj = {};
    obj[$(this).attr('name')] = this.checked == true ? 1 : 0;
    obj['_verify'] = 0;
    $.ajax({
        url: $(this).data('url'),
        type: 'post',
        dataType: 'json',
        data: obj,
        success: function (result) {
            layer.close(index);
            layer.msg(result.msg, {icon: 1});
        },
        error: function (xhr, state, errorThrown) {
            layer.close(index);
            layer.msg(state + '：' + errorThrown, {icon: 2});
        }
    });
});
// 通用全选
form.on('checkbox(*)', function (data) {
    $('.layui-table tbody input[lay-skin="primary"]').each(function (index, item) {
        item.checked = data.elem.checked;
    });
    form.render('checkbox');
});
// 通用提交
$('.ajax-submit').on('click', function () {
    var than = $(this);
    var form = $(this).parents('form');
    var index = layer.msg('提交中，请稍候', {
        icon: 16,
        time: false,
        shade: 0.3
    });
    than.attr('disabled', true);
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        dataType: 'json',
        data: $(data.form).serialize(),
        success: function (result) {
            if (result.code === 1 && result.url != '') {
                setTimeout(function () {
                    location.href = result.url;
                }, 1000);
            } else {
                than.attr('disabled', false);
            }
            layer.close(index);
            layer.msg(result.msg, {icon: 1});
        },
        error: function (xhr, state, errorThrown) {
            layer.close(index);
            layer.msg(state + '：' + errorThrown, {icon: 2});
        }
    });
    return false;
});
// 标签管理
$('body').on('click','.ajax-tags',function(){
    var data = $(this).data('id');
    console.log(data)
    layui.use(['jquery', 'tagsInput'], function () {
        var $ = layui.jquery;
        var tagsInput = layui.tagsInput;

        // BackSpace键可删除标签
        $('#'+ data).tagsInput({removeWithBackspace: true});
    });
});
// 数据表格专用
$('body').on('click','.ajax-action',function(){
    var url = $(this).attr('href');
    var index = layer.msg('请求中，请稍候', {
        icon: 16,
        time: false,
        shade: 0.3
    });
    $.ajax({
        url: url,
        type: 'post',
        dataType: 'json',
        success: function (result) {
            if (result.code === 1 && result.url != '') {
                setTimeout(function () {
                    location.href = result.url;
                }, 1000);
            }
            layer.close(index);
            layer.msg(result.msg, {icon: 1});
        },
        error: function (xhr, state, errorThrown) {
            layer.close(index);
            layer.msg(state + '：' + errorThrown, {icon: 2});
        }
    });
    return false;
});
// 数据表格专用
$('body').on('blur','.ajax-update',function(){
    // 参数
    var obj = {};
    obj[$(this).attr('name')] = $(this).val();
    obj['_verify'] = 0;
    var index = layer.msg('请求中，请稍候', {
        icon: 16,
        time: false,
        shade: 0.3
    });
    $.ajax({
        url: $(this).data('url'),
        type: 'post',
        dataType: 'json',
        data: obj,
        success: function (result) {
            if (result.code === 1) {
                layer.msg(result.msg, {icon: 1});
                setTimeout(function () {
                    location.reload();
                }, 1000);
            }
        },
        error: function (xhr, state, errorThrown) {
            layer.close(index);
            layer.msg(state + '：' + errorThrown, {icon: 2});
        }
    });
    return false;
});
//数据表格专用
$('body').on('click','.ajax-delete',function(){
    var url = $(this).attr('href');
    layer.confirm('确定操作？', {
        icon: 3,
        title: '提示'
    }, function (index) {
        var index = layer.msg('操作中，请稍候', {
            icon: 16,
            time: false,
            shade: 0.3
        });
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            success: function (result) {
                if (result.code === 1 && result.url != '') {
                    setTimeout(function () {
                        location.href = result.url;
                    }, 1000);
                }
                layer.close(index);
                layer.msg(result.msg, {icon: 1});
            },
            error: function (xhr, state, errorThrown) {
                layer.close(index);
                layer.msg(state + '：' + errorThrown, {icon: 2});
            }
        });
    });
    return false;
});
//数据表格专用
$('body').on('click','.ajax-detail',function(){
    var title = $(this).html();
    var url = $(this).attr('href');
    var index = layer.open({
        title: title,
        type: 2,
        content: url,
        success: function (layero, index) {
            setTimeout(function () {
                layer.tips('点击此处返回', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }, 500)
        }
    })
    layer.full(index);
    return false;
});
//数据表格专用
$('body').on('click','.ajax-iframe',function(){
    var title = $(this).html();
    var url = $(this).attr('href');
    var width = $(this).data('width');
    var height = $(this).data('height');
    if(navigator.userAgent.match(/(iPhone|iPod|iPad|Android|ios)/i)){
        var width = '100%';
        var height = '100%';
    };
    var index = layer.open({
        title: title,
        type: 2,
        anim: 0,
        shadeClose:true,
        area: [width, height],
        content: url,
        success: function(layero, index) {
            //获取IFRAME高度
            var iframeheight = layui.$(window).height();
            //获取浏览器高度
            var windowheight = layer.getChildFrame('html',index).outerHeight();
            //如果浏览器高度大于或者等于IFRAME
            if(windowheight <= iframeheight){
                if(navigator.userAgent.match(/(iPhone|iPod|iPad|Android|ios)/i)){
                    
                }else{
                    layer.iframeAuto(index);
                    layer.style(index, {
                        // 重新居中的样式
                        top: (layui.$(window).height() - layui.$(layero).height()) / 2
                    })
                }
            }
        },
    })
    return false;
});

// 通用批量
$('.ajax-batch').on('click', function () {
    var url = $(this).attr('href');
    var val = [];
    $('.layui-table tbody input[lay-skin="primary"]:checked').each(function (i) {
        val[i] = $(this).val();
    });
    if (val === undefined || val.length == 0) {
        layer.msg('请选择数据');
        return false;
    }
    var index = layer.msg('请求中，请稍候', {
        icon: 16,
        time: false,
        shade: 0.3
    });
    // 参数
    var obj = {};
    obj[$('.layui-table tbody input[lay-skin="primary"]:checked').attr('name')] = val;
    obj['_verify'] = 0;
    $.ajax({
        url: url,
        type: 'post',
        dataType: 'json',
        data: obj,
        success: function (result) {
            if (result.code === 1 && result.url != '') {
                setTimeout(function () {
                    location.reload();
                }, 1000);
            }
            layer.close(index);
            layer.msg(result.msg, {icon: 1});
        },
        error: function (xhr, state, errorThrown) {
            layer.close(index);
            layer.msg(state + '：' + errorThrown, {icon: 2});
        }
    });
    return false;
});

// 点击图片放大
$(document).off('click.tbImg').on('click.tbImg', '[tb-img]', function () {
    layer.photos({photos: {data: [{src: $(this).attr('src')}]}, shade: .1, closeBtn: true});
});

// 以下 管理员端
// 通用上传


upload.render({
    elem: '.ajax-admin-video',
    url: '/store/uploads/uploadVideo',
    accept: 'video', // 视频文件
    exts:'mp3|mp4',
    done: function (result) {
        // 上传完毕回调
        if (result.code === 1) {
            this.item.prev('input').val(result.url);
        } else {
            layer.msg(result.msg, {icon: 2});
        }
    }
});

//以下为  2021-05 版本
//单图上传
upload.render({
    elem: '.ajax-admin-images',
    url: '/store/uploads/uploadImage',
    before: function(obj) {
        layer.msg('上传中...', {
            icon: 16,
            shade: 0.01,
            time: 0
        })
    },
    done: function (result) {
        var data = this.item[0].id;
        // 上传完毕回调
        if (result.code === 1) {
            $('#removeImgage').removeClass('layui-hide');
            $('#'+ data +' .upload-name').addClass('layui-hide');
            $('#'+ data +' .upload-progress').addClass('layui-hide');
            $('#'+ data +' .upload-image').removeClass('layui-hide');
            $('#'+ data +' .upload-image').find('img').attr('src', result.url);
            $('#'+ data +' .upload-image').find('input').val(result.url);
            layer.msg('上传成功');
        } else {
            layer.msg(result.msg, {icon: 2});
        }
    },
    progress: function(n, elem, res, index){
        var data = this.item[0].id;
        $('#'+ data +' .upload-progress').removeClass('layui-hide');
        var percent = n + '%' //获取进度百分比
        element.progress(data, percent); //可配合 layui 进度条元素使用
        element.progress(data+'-'+ index, n + '%'); //进度条
    }
});
//单图删除
$("body").on("click","#removeImgage",function(){
    var data = $(this).context.dataset.id;
    $('#removeImgage').addClass('layui-hide');
    $('#'+ data +' .upload-name').removeClass('layui-hide');
    $('#'+ data +' .upload-progress').addClass('layui-hide');
    $('#'+ data +' .upload-image').addClass('layui-hide');
    $('#'+ data +' .upload-image').find('img').attr('src', '');
    $('#'+ data +' .upload-image').find('input').val('');
    //$(this).parent().remove();
});
// 多图上传
upload.render({
    elem: '.ajax-admin-photos',
    url: "/store/uploads/uploadImage", //改成您自己的上传接口
    multiple: true,
    acceptMime: 'image/*',
    size: 2048, //限制文件大小，单位 KB
    done: function(res){
        if (res.code === 1) {
            layer.msg(res.msg, {icon: 1});
        } else {
            layer.msg(res.msg, {icon: 5, anim: 6});
        }
        $('#photosView').append('<p class="photosList"><img src="'+ res.url +'" class="layui-upload-img"><a id="removeImg" class="layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon">&#xe640;</i>删除</a><input type="hidden" name="photo[]" value="' + res.url + '"/></p>');
    },
});

// 删除多图图片
$("body").on("click","#removeImg",function(){
    // layer.confirm('确定要删除么？',{
    //     btn:['确定','取消']
    // },function () {
    //     $(pre).parent().parent().remove();
    //     layer.closeAll('dialog');
    // })
    $(this).parent().remove();
});
/* 点击图片放大 */
layer.photos({
    photos: '#photosView',
    shade: .5,
    closeBtn: true
});
// 文件上传
var uploadListIns = upload.render({
    elem: '.ajax-admin-file'
    ,elemList: $('#file-lists') //列表元素对象
    ,url: '/store/uploads/uploadImage'
    ,accept: 'file'
    ,multiple: true
    ,number: 3
    ,auto: true
    ,choose: function(obj){
        var that = this;
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function(index, file, result){
            var tr = $(['<tr id="upload-'+ index +'">'
                ,'<td>'+ file.name +'<input type="hidden" name="file[]" value=""/></td>'
                ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
                ,'<td><div class="layui-progress" lay-filter="progress-demo"><div class="layui-progress-bar" lay-percent=""></div></div></td>'
                ,'<td>'
                ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                ,'<button class="layui-btn layui-btn-xs layui-btn-danger file-delete">删除</button>'
                ,'</td>'
                ,'</tr>'].join(''));
            //单个重传
            tr.find('.demo-reload').on('click', function(){
                obj.upload(index, file);
            });
            //删除
            tr.find('.demo-delete').on('click', function(){
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });
            that.elemList.append(tr);
            element.render('progress'); //渲染新加的进度条组件
        });
    }
    ,done: function(res, index, upload){ //成功的回调
        var that = this;
        console.log(res)
        if(res.code == 1){ //上传成功
            var tr = that.elemList.find('tr#upload-'+ index)
                ,tds = tr.children();
            //添加到input
            tds.eq(0).find('input').val(res.url);
            tds.eq(2).html('<span class="text-success">已完成</span>'); //清空操作
            //tds.eq(3).html(''); //清空操作
            delete this.files[index]; //删除文件队列已经上传成功的文件
            return;
        }else {
            var tr = that.elemList.find('tr#upload-'+ index)
                ,tds = tr.children();
            //添加到input
            tds.eq(0).find('input').val('');
            tds.eq(2).html('<span class="text-danger">已完成</span>'); //清空操作
            //tds.eq(3).html(''); //清空操作
            delete this.files[index]; //删除文件队列已经上传成功的文件
            return;
        }
        this.error(index, upload);
    }
    ,allDone: function(obj){ //多文件上传完毕后的状态回调
        console.log(obj)
    }
    ,error: function(index, upload){ //错误回调
        var that = this;
        var tr = that.elemList.find('tr#upload-'+ index)
            ,tds = tr.children();
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
    ,progress: function(n, elem, e, index){ //注意：index 参数为 layui 2.6.6 新增
        var percent = n + '%' //获取进度百分比
        element.progress('progress-demo', percent); //可配合 layui 进度条元素使用
        element.progress('progress-demo-'+ index, n + '%'); //执行进度条。n 即为返回的进度百分比
    }
});
//删除文件
$('body').on("click",".file-delete",function () {
    var pre = $(this);
    layer.confirm('确定要删除么？',{
        btn:['确定','取消']
    },function () {
        $(pre).parent().parent().remove();
        layer.closeAll('dialog');
    })
    //
});